import { useState, useEffect, useRef } from 'react'
/**
 * 节流的意义在于我们可以控制高频触发的事件在同一个时间周期内发生的频率
 * @param {any} params 必填，我们需要管理的状态
 * @param {object} options 可选，配置项，默认第一次不需要执行，最后一次需要执行
 * @param {number} options.delay 可选，时间周期，默认500ms
 * @param {boolean} options.leading 第一次调用函数时是否需要执行
 * @param {boolean} options.trailing 最后一次调用函数时是否需要执行
 */
export default function useThrottle(
  params,
  config = { leading: false, trailing: true, delay: 500 }
) {
  const [state, setState] = useState(params)

  const setting = useRef({
    timer: null,
    previous: 0,
    fnApply(args, now = 0) {
      setting.previous = now
      setState(args)
      setting.timer = 0
    },
    clearFn() {
      if (setting.timer) {
        clearTimeout(setting.timer)
        setting.timer = 0
      }
    },
  }).current

  const throttled = useRef(args => {
    const now = Date.now()
    if (!setting.previous && !config.leading) {
      setting.previous = now
    }
    const remaining = config.delay - (now - setting.previous)
    setting.clearFn()
    if (remaining <= 0) {
      return setting.fnApply(args, now)
    }
    if (config.trailing) {
      setting.timer = setTimeout(() => setting.fnApply(args), remaining)
    }
  })
  useEffect(() => {
    Object.assign(throttled.current, {
      cancel() {
        clearTimeout(setting.timer)
        setting.timer = 0
        setting.previous = 0
      },
    })
    return () => setting.clearFn()
  }, [throttled, setting])

  return [state, throttled.current]
}
